/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.cspimp.em.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.cspimp.em.domain.Team;
import me.zhengjie.modules.cspimp.em.domain.TeamMember;
import me.zhengjie.modules.cspimp.em.domain.vo.TeamVo;
import me.zhengjie.modules.cspimp.em.repository.TeamMemberRepository;
import me.zhengjie.modules.cspimp.em.service.dto.TeamMemberDto;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserInfoDto;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.em.repository.TeamRepository;
import me.zhengjie.modules.cspimp.em.service.TeamService;
import me.zhengjie.modules.cspimp.em.service.dto.TeamDto;
import me.zhengjie.modules.cspimp.em.service.dto.TeamQueryCriteria;
import me.zhengjie.modules.cspimp.em.service.mapstruct.TeamMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zmm
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-05-24
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TeamServiceImpl implements TeamService {

    private final TeamRepository teamRepository;
    private final TeamMapper teamMapper;
    private final TeamMemberRepository teamMemberRepository;
    private final UserRepository userRepository;
    private final UserService userService;

    @Override
    public Map<String, Object> queryAll(TeamQueryCriteria criteria, Pageable pageable) {
        List<Team> page = teamRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<TeamDto> teamList = new ArrayList<>();
        for (Team team : page) {
            TeamDto teamDto = new TeamDto();
            BeanUtils.copyProperties(team, teamDto);
            teamDto.setCaptainName(userRepository.findById(team.getCaptainId()).get().getUsername());
            List<TeamMember> teamMemberList = teamMemberRepository.findByTeamId(team.getId());
            List<TeamMemberDto> teamMembers = new ArrayList<>();
            if (!CollectionUtils.isEmpty(teamMemberList)) {
                for (TeamMember teamMember : teamMemberList) {
                    UserInfoDto user = userService.queryUserInfo(teamMember.getUserId());
                    TeamMemberDto teamMemberDto = new TeamMemberDto();
                    if (null != user) {
                        teamMemberDto.setUsername(user.getUsername());
                        teamMemberDto.setUserId(user.getUserId());
                        teamMemberDto.setTeamId(teamMember.getTeamId());
                        teamMemberDto.setDeptName(user.getDeptName());
                        teamMemberDto.setJobs(user.getJobs());
                        teamMemberDto.setPhone(user.getPhone());
                    }

                    teamMembers.add(teamMemberDto);
                }
            }
            teamDto.setTeamMemberList(teamMembers);
            teamList.add(teamDto);
        }
        return PageUtil.toPage(PageUtil.listPage(teamList, pageable));
    }

    @Override
    public List<TeamDto> queryAll(TeamQueryCriteria criteria) {
        return teamMapper.toDto(teamRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public TeamDto findById(Long id) {
        Team team = teamRepository.findById(id).orElseGet(Team::new);
        ValidationUtil.isNull(team.getId(), "Team", "id", id);
        TeamDto teamDto = new TeamDto();
        BeanUtils.copyProperties(team, teamDto);
        teamDto.setCaptainName(userRepository.findById(team.getCaptainId()).get().getUsername());
        List<TeamMember> teamMemberList = teamMemberRepository.findByTeamId(team.getId());
        List<TeamMemberDto> teamMembers = new ArrayList<>();
        if (!CollectionUtils.isEmpty(teamMemberList)) {
            for (TeamMember teamMember : teamMemberList) {
                UserInfoDto user = userService.queryUserInfo(teamMember.getUserId());
                TeamMemberDto teamMemberDto = new TeamMemberDto();
                if (null != user) {
                    teamMemberDto.setUsername(user.getUsername());
                    teamMemberDto.setUserId(user.getUserId());
                    teamMemberDto.setTeamId(teamMember.getTeamId());
                    teamMemberDto.setDeptName(user.getDeptName());
                    teamMemberDto.setJobs(user.getJobs());
                    teamMemberDto.setPhone(user.getPhone());
                }
                teamMembers.add(teamMemberDto);
            }
        }
        teamDto.setTeamMemberList(teamMembers);
        return teamDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TeamDto create(TeamVo resources) {
        Set<Long> teamMumberBids = resources.getTeamMemberIds();
        if (CollectionUtils.isEmpty(teamMumberBids)) {
            throw new BadRequestException("队员列表不能为空");
        }
        if (teamRepository.findByName(resources.getName()) != null) {
            throw new EntityExistException(Team.class, "name", resources.getName());
        }
        Team team = new Team();
        BeanUtils.copyProperties(resources, team);
        team.setCid(0l);
        teamRepository.save(team);
        //队员信息
        for (Long bid : teamMumberBids) {
            TeamMember teamMember = new TeamMember();
            teamMember.setCid(0l);
            teamMember.setTeamId(team.getId());
            teamMember.setUserId(bid);
            teamMemberRepository.save(teamMember);
        }
        return teamMapper.toDto(team);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TeamVo resources) {
        Team team = teamRepository.findById(resources.getId()).get();
        ValidationUtil.isNull(team.getId(), "Team", "id", resources.getId());
        Team t = teamRepository.findByName(resources.getName());
        if (t != null && !t.getId().equals(team.getId())) {
            throw new EntityExistException(Team.class, "name", resources.getName());
        }
        BeanUtils.copyProperties(resources, team);
        teamRepository.save(team);

        //先删除之前的队员
        teamMemberRepository.deleteByTeamId(team.getId());
        if (!CollectionUtils.isEmpty(resources.getTeamMemberIds())) {
            for (Long s : resources.getTeamMemberIds()) {
                TeamMember teamMember = teamMemberRepository.findByTeamIdAndUserId(team.getId(), s);
                if (null == teamMember) {
                    teamMember = new TeamMember();
                    teamMember.setCid(0l);
                    teamMember.setUserId(s);
                    teamMember.setTeamId(team.getId());
                    teamMemberRepository.save(teamMember);
                }

            }
        }
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            teamRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TeamDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TeamDto team : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put(" cid", team.getCid());
            map.put("队伍名称", team.getName());
            map.put("队伍职责", team.getDuty());
            map.put("队长bid", team.getCaptainId());
            map.put("创建日期", team.getCreateTime());
            map.put("更新时间", team.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}